package com.lzkj.baotouhousingfund.di.module;


import com.coderc.library.utils.Network;
import com.lzkj.baotouhousingfund.BuildConfig;
import com.lzkj.baotouhousingfund.app.App;
import com.lzkj.baotouhousingfund.app.Constants;
import com.lzkj.baotouhousingfund.http.PersistentCookieStore;
import com.lzkj.baotouhousingfund.http.api.ApiInterface;
import com.lzkj.baotouhousingfund.utils.SharedPreferenceUtil;

import java.io.File;
import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Chengs on 2017/4/2.
 */
@Module
public class HttpModule {


    @Singleton
    @Provides
    Retrofit.Builder provideRetrofitBuilder() {
        return new Retrofit.Builder();
    }

    @Singleton
    @Provides
    OkHttpClient.Builder provideOkHttpClientBuilder() {
        return new OkHttpClient.Builder();
    }

    @Singleton
    @Provides
    Retrofit provideHomeRetrofit(Retrofit.Builder builder, OkHttpClient client) {
        return createRetrofit(builder, client, ApiInterface.HOST);
    }

//    @Singleton
//    @Provides
//    @EduUrl
//    Retrofit provideEduRetrofit(Retrofit.Builder builder, OkHttpClient client) {
//        return createRetrofit(builder, client, EduApiInterface.HOST);
//    }

    @Singleton
    @Provides
    ApiInterface provideApiInterface(Retrofit retrofit) {
        return retrofit.create(ApiInterface.class);
    }

//    @Singleton
//    @Provides
//    EduApiInterface provideEduApiInterface(@EduUrl Retrofit retrofit) {
//        return retrofit.create(EduApiInterface.class);
//    }


    @Singleton
    @Provides
    OkHttpClient provideOkHttpClient(OkHttpClient.Builder builder) {
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
            builder.addInterceptor(loggingInterceptor);
        }
        File cacheFile = new File(Constants.PATH_CACHE);
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);

        Interceptor cacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!Network.isAvailable(App.getInstance().getApplicationContext())) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();

                }
                Response response = chain.proceed(request);
//                LogUtil.d("HTTP_STATUS", "状态码=========" + response.code());
//                if (response.code() == Constants.STATUS_OTHER_DEVICE_LOGIN) {
//                    EventBus.getDefault().post(new OtherLoginEvent());
//                    SharedPreferenceUtil.setReLoginClick(false);
//                }
                if (Network.isAvailable(App.getInstance().getApplicationContext())) {
                    int maxAge = 0;
                    // 有网络时,不缓存,最大保存时长为0
                    response.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .removeHeader("Pragma")
                            .build();
                } else {
                    // 无网络时，设置超时为4周
                    int maxStale = 60 * 60 * 24 * 28;
                    response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" +
                                    maxStale)
                            .removeHeader("Pragma")
                            .build();
                }
                return response;
            }

        };

        //Header
        Interceptor headerInterceptor = chain -> {
            Request originalRequest = chain.request();
            String token = SharedPreferenceUtil.getToken();
            Request.Builder requestBuilder = originalRequest.newBuilder()
                    .header("AppType", "TPOS")
                    .header("Content-Type", "application/json")
                    .header("Accept", "application/json")
                    .method(originalRequest.method(), originalRequest.body());
            Request request = requestBuilder.build();
            return chain.proceed(request);
        };


        //设置缓存
        builder.addNetworkInterceptor(cacheInterceptor);
        builder.addInterceptor(cacheInterceptor);
        builder.addInterceptor(headerInterceptor);//设置头
//        builder.addInterceptor(addQueryParameterInterceptor);//公共参数
        builder.cache(cache);
        //设置超时
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);

        //Cookie持久化
        CookieHandler cookieHandler = new CookieManager(new PersistentCookieStore(App.getInstance
                ().getApplicationContext()),
                CookiePolicy.ACCEPT_ALL);
        builder.cookieJar(new JavaNetCookieJar(cookieHandler));
        return builder.build();
    }

    private Retrofit createRetrofit(Retrofit.Builder builder, OkHttpClient client, String url) {
        return builder
                .baseUrl(url)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
    }

}
